package com.act;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bean.BaseBean;
import com.bean.CheckCode;
import com.common.Constant;
import com.common.TextHttpResponseHandler;
import com.control.UserControl;
import com.fragment.MineFragment;
import com.xike.kyt.R;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class BindMobileAct extends BaseAct implements OnClickListener {
	private static final int MSG_TIMER_DATA = 1;// 记时
	private static final int TIME_REMAIN = 60;// 倒计时时间
	LinearLayout layout_step1, layout_step2;

	EditText edt_phoneNum, edt_checkCode;
	TextView tv_checkCode;

	TextView tv_phoneNum;
	EditText edt_msgCode;
	TextView tv_resend;
	TextView tv_tips;

	Button btn_next;

	int step = 1;

	String phoneNum;

	int time_remain = TIME_REMAIN;
	Timer timer;

	CheckCode checkCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_bind_mobile);
		initViews();
	}

	@Override
	protected void initViews() {

		findViewById(R.id.headTitle_tv_back).setOnClickListener(this);

		layout_step1 = (LinearLayout) findViewById(R.id.bindMobile_layout_step1);
		layout_step2 = (LinearLayout) findViewById(R.id.bindMobile_layout_step2);
		layout_step2.setVisibility(View.GONE);

		edt_phoneNum = (EditText) findViewById(R.id.bindMobile_edt_phoneNum);
		edt_checkCode = (EditText) findViewById(R.id.bindMobile_edt_checkCode);
		tv_checkCode = (TextView) findViewById(R.id.bindMobile_tv_checkCode);
		tv_checkCode.setOnClickListener(this);
		edt_msgCode = (EditText) findViewById(R.id.bindMobile_edt_msgCode);
		tv_checkCode.setText(getRandomString());

		tv_tips = (TextView) findViewById(R.id.bindMobile_tv_tips);
//		tv_tips.setText("温馨提示：\n1.绑定的手机号用于与专家通话\n2.绑定的手机号可作为登录手机号使用");
		tv_tips.setText("温馨提示：\n1.绑定的手机号用于与专家通话");

		edt_checkCode = (EditText) findViewById(R.id.bindMobile_edt_checkCode);
		tv_phoneNum = (TextView) findViewById(R.id.bindMobile_tv_phoneNum);
		tv_resend = (TextView) findViewById(R.id.bindMobile_tv_resendMsgCode);
		tv_resend.setOnClickListener(this);

		btn_next = (Button) findViewById(R.id.bindMobile_btn_next);
		btn_next.setOnClickListener(this);

		String strBindedNum = UserControl.getLoginUserBindMobile();
		if (StringUtil.isNotNull(strBindedNum)) {
			edt_phoneNum.setText(strBindedNum);
			edt_phoneNum.setSelection(strBindedNum.length());
		}

	}

	@Override
	protected void updateViews() {

	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_TIMER_DATA:
				if (time_remain > 0) {
					tv_resend.setText(time_remain + "秒后重发");
					// tv_resend.setText(Html.fromHtml("<u>" + time_remain + "秒后重发" + "</u>"));
				} else {
					timer.cancel();
					timer = null;
					tv_resend.setText("重新获取验证码");
					// tv_resend.setText(Html.fromHtml("<u>" + "重新获取验证码" + "</u>"));
					tv_resend.setEnabled(true);
				}
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.headTitle_tv_back:
			if (step == 2) {
				step = 1;
				layout_step2.setVisibility(View.GONE);
				layout_step1.setVisibility(View.VISIBLE);
				tv_tips.setVisibility(View.VISIBLE);
				btn_next.setText("下一步");
				tv_checkCode.setText(getRandomString());
				edt_checkCode.setText("");
			} else {
				finish();
			}
			break;
		case R.id.bindMobile_tv_resendMsgCode:
			if (time_remain <= 0) {
				serviceSendMsgCode();
			}
			break;
		case R.id.bindMobile_btn_next:
			if (step == 1) {
				if (checkStep1Input()) {
					serviceSendMsgCode();
				}
			} else if (step == 2) {
				if (checkStep2Input()) {
					serviceBindMobile();
				}
			}
			break;
		case R.id.bindMobile_tv_checkCode:
			tv_checkCode.setText(getRandomString());
			break;

		default:
			break;
		}
	}

	private void serviceSendMsgCode() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("mobile", MyUtil.getEditTextContent(edt_phoneNum)));
		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_BIND_PHONE_CODE, params);
		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(BindMobileAct.this, getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				CheckCode result = gson.fromJson(responseString, CheckCode.class);
				tv_resend.setEnabled(false);
				dealSendMsgResult(result);
				super.onSuccess(statusCode, headers, responseString);
			}

		});
	}

	private void dealSendMsgResult(CheckCode result) {
		if (result != null && result.isReturnTrue()) {
			checkCode = result;
			step = 2;
			btn_next.setText("确定");
			layout_step1.setVisibility(View.GONE);
			layout_step2.setVisibility(View.VISIBLE);
			String strShowPhoneNum = phoneNum.substring(0, 3) + "****" + phoneNum.substring(7, 11);
			tv_phoneNum.setText(strShowPhoneNum);
			startCountDown();
			mToast.showToast(BindMobileAct.this, "短信效验码已发送");
		} else {
			if (result == null) {
				mToast.showToast(BindMobileAct.this, getString(R.string.net_error));
			} else {
				mToast.showToast(BindMobileAct.this, result.getError_description());
			}
		}

	}

	private void serviceBindMobile() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("mobile", MyUtil.getEditTextContent(edt_phoneNum)));
		params.add(new BasicNameValuePair("code", MyUtil.getEditTextContent(edt_msgCode)));
		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_BIND_PHONE, params);
		client.put(strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(BindMobileAct.this, getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null && result.isReturnTrue()) {
					mToast.showToast(BindMobileAct.this, "绑定成功");
					UserControl.saveLoginUserBindMobile(phoneNum);
					setResult(1);
					finish();
				} else {
					if (result == null) {
						mToast.showToast(BindMobileAct.this, getString(R.string.net_error));
					} else {
						mToast.showToast(BindMobileAct.this, result.getError_description());
					}
				}
				super.onSuccess(statusCode, headers, responseString);
			}

		});

	}

	/**
	 * @description:开启倒计时
	 * @user wzl email:wzl200711402@163.com
	 * @date 2014-2-13
	 */
	private void startCountDown() {
		tv_resend.setEnabled(false);
		tv_resend.setText(time_remain + "秒后重发");
		tv_resend.setSelected(false);
		if (timer == null) {
			time_remain = TIME_REMAIN;
			timer = new Timer();
			timer.schedule(new TimerTask() {

				@Override
				public void run() {
					if (time_remain > 0) {
						time_remain--;
						Message msg = new Message();
						msg.what = MSG_TIMER_DATA;
						handler.sendMessage(msg);
					}

				}
			}, 1000, 1000);
		}
	}

	private boolean checkStep1Input() {
		String strPhoneNum = MyUtil.getEditTextContent(edt_phoneNum);
		if (!StringUtil.isNotNull(strPhoneNum)) {
			mToast.showToast(this, "请输入手机号");
			return false;
		}

		if (!MyUtil.isPhoneNumberValid(strPhoneNum)) {
			mToast.showToast(this, "请输入有效的手机号");

			return false;
		}

		phoneNum = strPhoneNum;

		String strInputCheckCode = MyUtil.getEditTextContent(edt_checkCode);
		if (!StringUtil.isNotNull(strInputCheckCode)) {
			mToast.showToast(this, "请输入验证码");
			return false;
		}

		String strCheckCode = tv_checkCode.getText().toString();
		if (!strCheckCode.equals(strInputCheckCode)) {
			tv_checkCode.setText(getRandomString());
			mToast.showToast(this, "您输入的验证码有误，请重新输入");
			return false;
		}

		return true;
	}

	private boolean checkStep2Input() {
		String str_code = MyUtil.getEditTextContent(edt_msgCode);
		if (!StringUtil.isNotNull(str_code)) {
			mToast.showToast(this, "请输入效验码");
			return false;
		}
		if (checkCode == null) {
			mToast.showToast(this, "效验码获取失败，请重新获取");
			return false;
		}
		if (!str_code.equals(checkCode.getCode())) {
			mToast.showToast(this, "效验码输入错误");
			return false;
		}
		return true;
	}

	private String getRandomString() {
		long num = (long) (Math.random() * 9000 + 1000);
		return String.valueOf(num);
	}

}
